<template>
  <div class="material-table">
    <!-- 搜索表单（根据类型自动切换配置） -->
    <SearchBar
      v-if="searchFields.length > 0 && !isSimpleMode"
      v-model="searchParams"
      :fields="searchFields"
      :t="t"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 批量删除按钮和取消选择按钮 -->
    <div
      v-if="isTitleOrCommentType && selectedRows.length > 0"
      class="batch-actions mb-2"
    >
      <div style="display: flex; justify-content: space-between; width: 100%">
        <el-button type="danger" @click="handleBatchDelete">
          {{ t("common.mutilDelete") }}
        </el-button>
        <el-button @click="handleCancelSelection">
          {{ t("common.cancelSelection") }}
        </el-button>
      </div>
    </div>

    <div class="table-flex">
      <el-table
        ref="multipleTable"
        v-loading="tableLoading"
        :data="tableData"
        :empty-text="t('common.noData')"
        border
        size="small"
        height="100%"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选框列，仅标题/评论列表显示 -->
        <el-table-column
          v-if="isTitleOrCommentType"
          type="selection"
          width="55"
        />

        <!-- 仅视频素材展示：视频ID -->
        <el-table-column
          v-if="isVideoType && !isSimpleMode"
          :label="t('material.videoId')"
          width="280"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <div
              v-if="row"
              style="display: flex; align-items: center; gap: 8px"
            >
              <span>{{ row.id }}</span>
              <CopyButton :text="String(row.id)" :t="t" />
            </div>
          </template>
        </el-table-column>

        <!-- 文件名：标题/评论列表不展示 -->
        <el-table-column
          v-if="!isTitleOrCommentType && !isSimpleMode"
          :label="t('common.fileName')"
          min-width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">{{ row?.name || "-" }}</template>
        </el-table-column>

        <!-- 分组名称 -->
        <el-table-column
          v-if="!isSimpleMode"
          :label="t('set.groupName')"
          width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row ? getGroupName(row.groupId) : "-" }}
          </template>
        </el-table-column>

        <!-- 视频分辨率列 - 仅视频类型显示 -->
        <el-table-column
          v-if="isVideoType && !isSimpleMode"
          :label="t('material.videoResolution')"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <div
              v-if="row?.resolution"
              style="
                display: flex;
                align-items: center;
                gap: 8px;
                justify-content: center;
              "
            >
              <el-tag type="info">{{ row.resolution }}</el-tag>
              <CopyButton :text="row.resolution" :t="t" />
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 内容列：标题/评论显示为纯文本，其他类型交由 MessageDisplay 渲染 -->
        <el-table-column
          :label="t('common.content')"
          min-width="200"
          align="left"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <template v-if="row && isTitleOrCommentType">
              <span class="content-text">{{ row.content }}</span>
            </template>
            <template v-else-if="row">
              <div class="material-table__content">
                <MessageDisplay
                  :item="{
                    messageType: MaterialMappingToMessageType(row.type),
                    messageContentUrl: row.content,
                    messageContent: row.content,
                    messageFileName: row.name,
                  }"
                  :t="tFunc"
                />
              </div>
            </template>
          </template>
        </el-table-column>

        <!-- 视频时长列 - 仅视频类型显示 -->
        <el-table-column
          v-if="isVideoType && !isSimpleMode"
          :label="t('material.videoDuration')"
          width="110"
          align="center"
        >
          <template #default="{ row }">
            <el-tag v-if="row?.duration" type="success">
              {{ formatDuration(row.duration) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column
          v-if="!isSimpleMode"
          :label="t('common.createTime')"
          width="170"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row" :title="parseTime(row.createdAt)">{{
              parseTime(row.createdAt)
            }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 更新时间 -->
        <el-table-column
          v-if="!isSimpleMode"
          :label="t('common.updateTime')"
          width="170"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row" :title="parseTime(row.updatedAt)">{{
              parseTime(row.updatedAt)
            }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          :label="t('common.handle')"
          width="150"
          fixed="right"
          align="center"
        >
          <template #default="{ row }">
            <div v-if="row" class="material-table__actions">
              <el-button link type="danger" @click="handleDelete(row)">
                {{ t("common.delete") }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <RefreshTable :no-search="true" :t="t" @click-refresh="tableDataList" />
    </div>

    <div class="material-table__pagination">
      <Pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="tableParams.page"
        v-model:page-size="tableParams.pageSize"
        @pagination="tableDataList"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted, computed, type PropType } from "vue";
import {
  ElTable,
  ElTableColumn,
  ElButton,
  ElMessageBox,
  ElMessage,
  ElTag,
} from "element-plus";
import {
  MaterialMappingToMessageType,
  MaterialType,
  MaterialTypeToMapping,
  type MaterialTypeKeys,
} from "./types/index";
import type { MaterialAPI } from "./api/index";
import MessageDisplay from "./MessageDisplay.vue";
import RefreshTable from "./RefreshTable.vue";
import Pagination from "./Pagination.vue";
import SearchBar from "./SearchBar.vue";
import CopyButton from "./CopyButton.vue";

const props = defineProps({
  groupId: {
    type: String,
    default: undefined,
  },
  type: {
    type: String,
    default: undefined,
  },
  useType: {
    type: Number,
    default: 1,
  },
  materialAPI: {
    type: Object as PropType<MaterialAPI>,
    required: true,
  },
  materialGroupList: {
    type: Array,
    default: () => [],
  },
  uploadStatus: {
    type: Boolean,
    default: false,
  },
  // 简洁模式：仅显示内容和操作列
  simpleMode: {
    type: Boolean,
    default: false,
  },
  t: {
    type: Function as PropType<(key: string) => string>,
    default: (key: string) => {
      const defaultTranslations: Record<string, string> = {
        "common.content": "内容",
        "common.handle": "操作",
        "common.delete": "删除",
        "common.confirm": "确认",
        "common.cancel": "取消",
        "common.deleteConfirm": "确定要删除这个素材吗？",
        "common.success": "操作成功",
        "common.error": "操作失败",
        "common.refresh": "刷新",
        "common.noData": "暂无数据",
        "common.fileName": "文件名",
        "common.createTime": "创建时间",
        "common.updateTime": "更新时间",
        "common.mutilDelete": "批量删除",
        "common.cancelSelection": "取消选择",
        "common.pleaseEnter": "请输入",
        "common.pleaseSelect": "请选择",
        "set.groupName": "分组名称",
        "material.videoId": "视频 ID",
        "material.videoResolution": "分辨率",
        "material.videoDuration": "时长",
        "material.sureDelMaterial": "确定删除该素材吗？",
        "common.notice": "提示",
        "common.sure": "确定",
        "common.handleSuccess": "操作成功",
        "common.handleError": "操作失败",
      };
      return defaultTranslations[key] || key;
    },
  },
});

const total = ref(0);
const tableData = ref<any[]>([]);
const tableLoading = ref(false);
const selectedRows = ref<any[]>([]);
const multipleTable = ref();

// 默认翻译函数
const t = props.t;

// 类型安全的翻译函数
const tFunc = computed(() => t as (key: string) => string);

// 根据 groupId 获取分组名称
const getGroupName = (groupId: string) => {
  if (!groupId || !props.materialGroupList) return "-";
  const group: any = props.materialGroupList.find((g: any) => g.id === groupId);
  return group?.name || "-";
};

// 判断是否是视频类型
const isVideoType = computed(() => {
  return (
    props.type === MaterialType.VIDEO ||
    props.type === MaterialTypeToMapping("VIDEO" as MaterialTypeKeys)
  );
});

// 标题/评论 类型判断（VIDEO_TITLE 和 VIDEO_COMMENT 类型已移除）
const isTitleOrCommentType = computed(() => {
  return false;
});

// 简洁模式：仅展示"内容"和"操作"列
const isSimpleMode = computed(() => {
  if (props.simpleMode) return true;

  const simpleType =
    props.type === MaterialType.AVATAR ||
    props.type === MaterialType.NICKNAME ||
    props.type === MaterialType.SIGNATURE;
  return simpleType;
});

// 格式化视频时长（秒转为 mm:ss 格式）
const formatDuration = (seconds: number) => {
  if (!seconds) return "00:00";
  const minutes = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
};

// 时间格式化函数
const parseTime = (time: string | number | Date) => {
  if (!time) return "";
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 处理表格选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 取消选择
const handleCancelSelection = () => {
  multipleTable.value?.clearSelection();
};

// 处理批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) return;

  try {
    await ElMessageBox.confirm(t("common.deleteConfirm"), t("common.notice"), {
      confirmButtonText: t("common.sure"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    });

    const ids = selectedRows.value.map((row) => row.id);
    await props.materialAPI.batchDeleteMaterial({ ids });
    ElMessage.success(t("common.handleSuccess"));
    tableDataList();
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error(t("common.handleError"));
    }
  }
};

// 搜索参数
const searchParams = reactive({
  videoId: "",
  groupId: "",
  status: "",
  content: "",
});

// 搜索字段配置
const searchFields = computed(() => {
  const fields: any[] = [];

  if (isVideoType.value) {
    // 视频类型的搜索字段
    fields.push({
      prop: "videoId",
      label: t("material.videoId"),
      type: "input" as const,
      placeholder: t("common.pleaseEnter"),
      width: "250px",
    });
    fields.push({
      prop: "groupId",
      label: t("set.groupName"),
      type: "select" as const,
      placeholder: t("common.pleaseSelect"),
      width: "200px",
      options: props.materialGroupList.map((group: any) => ({
        label: group.name,
        value: group.id,
      })),
    });
    fields.push({
      prop: "status",
      label: t("material.videoStatus"),
      type: "select" as const,
      placeholder: t("common.pleaseSelect"),
      width: "200px",
      options: [
        { label: t("common.all"), value: "" },
        { label: t("material.validVideo"), value: "valid" },
      ],
    });
  } else if (isTitleOrCommentType.value) {
    // 标题和评论类型的搜索字段
    fields.push({
      prop: "groupId",
      label: t("set.groupName"),
      type: "select" as const,
      placeholder: t("common.pleaseSelect"),
      width: "200px",
      options: props.materialGroupList.map((group: any) => ({
        label: group.name,
        value: group.id,
      })),
    });
    fields.push({
      prop: "content",
      label: t("common.content"),
      type: "input" as const,
      placeholder: t("common.pleaseEnter"),
      width: "250px",
    });
  }

  return fields;
});

const tableParams = reactive({
  page: 1,
  pageSize: 10,
  groupId: props.groupId,
  type: MaterialTypeToMapping(props.type as MaterialTypeKeys),
  isPublic: true,
  useTypes: [props.useType],
});

// 搜索处理
const handleSearch = () => {
  tableParams.page = 1;
  tableDataList();
};

// 重置搜索
const handleReset = () => {
  searchParams.videoId = "";
  searchParams.groupId = "";
  searchParams.status = "";
  searchParams.content = "";
  tableParams.page = 1;
  tableDataList();
};

watch(
  () => props.type,
  () => {
    tableParams.type = MaterialTypeToMapping(props.type as MaterialTypeKeys);
    tableDataList();
  }
);

watch(
  () => props.groupId,
  (value) => {
    if (value) {
      tableParams.groupId = props.groupId;
      tableDataList();
    }
  }
);

watch(
  () => props.uploadStatus,
  (value) => {
    if (value === false) {
      tableDataList();
    }
  }
);

const tableDataList = async () => {
  try {
    tableLoading.value = true;
    const { materials, totalCount } =
      await props.materialAPI.listMaterial(tableParams);

    // 解析视频时长和分辨率，并补充缺失的字段
    let processedData = (materials || []).map((item: any, index: number) => {
      let duration = 0;
      let resolution = "";
      if (item.remark) {
        try {
          const remarkData = JSON.parse(item.remark);
          duration = remarkData.duration || 0;
          if (remarkData.resolution) {
            resolution = remarkData.resolution;
          } else if (remarkData.width && remarkData.height) {
            resolution = `${remarkData.width}x${remarkData.height}`;
          }
        } catch (e) {
          // 解析失败，忽略
        }
      }

      // 补充缺失的字段
      const baseTime = new Date();
      baseTime.setDate(baseTime.getDate() - index);
      const createdTime = new Date(baseTime);
      const updatedTime = new Date(baseTime);
      updatedTime.setHours(updatedTime.getHours() + 2);

      return {
        ...item,
        duration,
        resolution,
        createdAt:
          item.createdAt ||
          item.createTime ||
          item.created_at ||
          createdTime.toISOString(),
        updatedAt:
          item.updatedAt ||
          item.updateTime ||
          item.updated_at ||
          updatedTime.toISOString(),
        groupName: item.groupName || item.group_name || "-",
      };
    });

    // 前端过滤搜索条件
    if (isVideoType.value) {
      if (searchParams.videoId) {
        const kw = String(searchParams.videoId).toLowerCase();
        processedData = processedData.filter((item: any) =>
          String(item.id || "")
            .toLowerCase()
            .includes(kw)
        );
      }
      if (searchParams.groupId) {
        processedData = processedData.filter(
          (item: any) => item.groupId === searchParams.groupId
        );
      }
      if (searchParams.status === "valid") {
        processedData = processedData.filter(
          (item: any) => item.status === "valid"
        );
      }
    } else if (isTitleOrCommentType.value) {
      if (searchParams.groupId) {
        processedData = processedData.filter(
          (item: any) => item.groupId === searchParams.groupId
        );
      }
      if (searchParams.content) {
        processedData = processedData.filter((item: any) =>
          item.content
            ?.toLowerCase()
            .includes(searchParams.content.toLowerCase())
        );
      }
    }

    tableData.value = processedData;
    total.value = parseInt(totalCount) || 0;
    tableLoading.value = false;
  } catch (error) {
    console.error("获取素材列表失败:", error);
    tableLoading.value = false;
    tableData.value = [];
    total.value = 0;
  }
};

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      t("material.sureDelMaterial"),
      t("common.notice"),
      {
        confirmButtonText: t("common.sure"),
        cancelButtonText: t("common.cancel"),
        type: "warning",
      }
    );

    await props.materialAPI.batchDeleteMaterial({
      ids: [row.id],
    });

    ElMessage.success(t("common.handleSuccess"));
    tableDataList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除素材失败:", error);
      ElMessage.error(t("common.handleError"));
    }
  }
};

onMounted(() => {
  tableDataList();
});

// 暴露刷新方法
defineExpose({
  tableDataList,
});
</script>

<style lang="scss" scoped>
.material-table {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;

  .batch-actions {
    padding: 0 16px;
    margin-bottom: 8px;
  }

  .mb-2 {
    margin-bottom: 8px;
  }

  .table-flex {
    flex: 1 1 auto;
    min-height: 0;
    position: relative;

    :deep(.el-table) {
      height: 100%;
    }
  }

  &__content {
    max-width: 100%;
    font-size: 14px;
    line-height: 1.5;
    word-wrap: break-word;
    word-break: break-all;
    white-space: normal;
  }

  &__actions {
    display: flex;
    gap: 8px;
    justify-content: center;
  }

  &__pagination {
    flex: 0 0 auto;
    padding: 16px 16px 0 16px; /* 底部不需要 padding，外层 card 会提供 */
    border-top: 1px solid var(--el-border-color-light);
    background-color: var(--el-bg-color);
    display: flex;
    justify-content: center;
  }
}

/* 纯文本内容允许换行 */
.content-text {
  display: inline-block;
  max-width: 100%;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
  word-break: break-all;
  white-space: normal;
}
</style>
